import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:setting_flutter/utils/Auth.dart';
import 'package:setting_flutter/utils/RequestDio.dart';
import 'components/order_tab_bar.dart';
import 'components/order_item.dart';

class OrderPage extends StatefulWidget {
  const OrderPage({super.key});

  @override
  State<OrderPage> createState() => _OrderPageState();
}

class _OrderPageState extends State<OrderPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final List<String> _tabs = ['全部', '待付款', '待发货', '待收货', '待评价'];
  // ListView组件控制器
  final ScrollController _scrollController = ScrollController();
  //loading框
  bool _isLoading = false;
  //是否还有更多
  bool _hasMore = true;

  //第一步:建立通道 通道名称需要和鸿蒙端注册的一致
  final _platform = MethodChannel('mk_project');

  //定义请求参数
  Map<String, dynamic> params = {'page': 1, 'pageSize': 10, 'orderState': 0};

//订单列表
  List<Map<String, dynamic>> _orderList = [];
  // {
  //   'id': '1001',
  //   'createTime': '2024-01-15 18:03:24',
  //   'payType': 1,
  //   'orderState': 1,
  //   'payLatestTime': '2024-01-15 19:03:24',
  //   'postFee': 0,
  //   'payMoney': 25.00,
  //   'totalMoney': 25.00,
  //   'totalNum': 1,
  //   'skus': [
  //     {
  //       'id': 'sku001',
  //       'spuId': 'spu001',
  //       'name': 'DIOR 迪奥 LADY D-JOY 中号羊皮格纹女士手提包',
  //       'quantity': 1,
  //       'image': 'assets/images/bag.png',
  //       'realPay': 25.00,
  //       'curPrice': 25.00,
  //       'totalMoney': 25.00,
  //       'properties': [
  //         {'propertyMainName': '颜色', 'propertyValueName': '黑色'},
  //         {'propertyMainName': '尺码', 'propertyValueName': 'L'}
  //       ],
  //       'attrsText': '黑色 L'
  //     }
  //   ],
  //   'payChannel': 1,
  //   'countdown': 3600
  // },
  // {
  //   'id': '1002',
  //   'createTime': '2024-01-15 17:03:24',
  //   'payType': 1,
  //   'orderState': 2,
  //   'payLatestTime': '2024-01-15 18:03:24',
  //   'postFee': 0,
  //   'payMoney': 25.00,
  //   'totalMoney': 25.00,
  //   'totalNum': 1,
  //   'skus': [
  //     {
  //       'id': 'sku002',
  //       'spuId': 'spu001',
  //       'name': 'DIOR 迪奥 LADY D-JOY 中号羊皮格纹女士手提包',
  //       'quantity': 1,
  //       'image': 'assets/images/bag.png',
  //       'realPay': 25.00,
  //       'curPrice': 25.00,
  //       'totalMoney': 25.00,
  //       'properties': [
  //         {'propertyMainName': '颜色', 'propertyValueName': '红色'},
  //         {'propertyMainName': '尺码', 'propertyValueName': 'M'}
  //       ],
  //       'attrsText': '红色 M'
  //     }
  // ],
  // 'payChannel': 1,
  // 'countdown': 3600
  // }
  // ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabs.length, vsync: this);
    _tabController.addListener(_handleTabChange);

    _scrollController.addListener(_handleScroll);

    //获取鸿蒙端传递的token
    _getToken();
  }

//tab栏切换事件
  _handleTabChange() async {
    if (_tabController.indexIsChanging) {
      setState(() {
        //拿到状态
        params['orderState'] = _tabController.index;
        //重置page
        params['page'] = 1;
        //清空 列表
        _orderList = [];
        _hasMore = true;
      });
      await _getOrderList();
    }
  }

//触底加载更多
  _handleScroll() async {
    //如果在加载中,则不触底
    if (_isLoading) return;

    if (!_isLoading &&
        _hasMore &&
        _scrollController.position.pixels >=
            _scrollController.position.maxScrollExtent - 50) {
      //加载更多
      // _sendMessage('触底了');
      setState(() {
        _isLoading = true;
      });
      params['page'] = (params['page'] as int) + 1;
      try {
        final res = await requestDio.get('/member/order', params: params);
        final newItem = List<Map<String, dynamic>>.from(res['items']);
        setState(() {
          _orderList.addAll(newItem);
          _isLoading = false;
          _hasMore = newItem.isNotEmpty;
        });
      } catch (e) {
        _sendMessage(e.toString());
      }
    }
  }

  // @override
  // void didUpdateWidget(covariant OrderPage oldWidget) {
  //   super.didUpdateWidget(oldWidget);
  //   _getOrderList();
  //   _sendMessage('didUpdateWidget执行了');
  // }

  // @override
  // void didChangeDependencies() {
  //   super.didChangeDependencies();
  //   _getOrderList();
  //   _sendMessage('didChangeDependencies执行了');
  // }

  @override
  void dispose() {
    _tabController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  //测试:flutter端传递数据给到鸿蒙端
  _sendMessage(String msg) {
    //第二步:调用通道方法invokeMethod
    //参数1:保证和鸿蒙侧的方法一致showMessage
    _platform.invokeMethod('showMessage', msg);
  }

//获取鸿蒙侧传递的token
  _getToken() async {
    String token = await _platform.invokeMethod('getToken');
    if (token.isNotEmpty) {
      Auth.token = token;
      _sendMessage(token);
      //发请求获取订单列表数据
      _getOrderList();
    }
  }

//获取订单列表数据
  _getOrderList() async {
    try {
      setState(() {
        _isLoading = true;
        _orderList = [];
      });
      final res = await requestDio.get('/member/order', params: params);
      //List.from重新构造List,想当与js数组中的map方法
      _orderList = List<Map<String, dynamic>>.from(res['items']);
      setState(() {
        _isLoading = false;
      });
    } catch (e) {
      _sendMessage(e.toString());
    }
  }

//加载状态builder
  Widget _buildLoadingIndicator() {
    //没有更多数据了builder
    if (!_hasMore) {
      return const Padding(
        padding: EdgeInsets.only(bottom: 100),
        child: Center(
          child: Text(
            '没有更多数据了',
            style: TextStyle(
              color: Color(0xFF999999),
              fontSize: 12,
            ),
          ),
        ),
      );
    }

//加载loading builder
    if (_isLoading) {
      return Padding(
          padding: EdgeInsets.only(bottom: 80),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                CircularProgressIndicator(),
                Text('加载中...'),
              ],
            ),
          ));
    }

    return const SizedBox();
  }

//下拉刷新
  Future<void> _onRefresh() async {
    setState(() {
      params["page"] = 1;
      _hasMore = true;
    });
    await _getOrderList();
    _sendMessage('刷新成功');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(0xFFF5F5F5),
        body: RefreshIndicator(
          onRefresh: _onRefresh,
          child: Column(
            children: [
              OrderTabBar(
                tabs: _tabs,
                controller: _tabController,
              ),
              Expanded(
                child: ListView.builder(
                  controller: _scrollController,
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  itemCount: _orderList.length + 1,
                  itemBuilder: (context, index) {
                    //没有数据了或者是正在加载中
                    if (index == _orderList.length) {
                      return _buildLoadingIndicator();
                    }
                    //展示列表数据
                    return OrderItem(
                      orderInfo: _orderList[index],
                    );
                  },
                ),
              ),
            ],
          ),
        ));
  }
}
